import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_app/Toast.dart';

class SharedPreferencesUtil {
  final String spKey = "MyFlutterApp";
  SharedPreferences sharedPreferences;

  factory SharedPreferencesUtil() => _getInstance();

  static SharedPreferencesUtil _instance;

  static SharedPreferencesUtil get instance => _getInstance();

  SharedPreferencesUtil._internal() {
    getSp();
  }

  static SharedPreferencesUtil _getInstance() {
    if (_instance == null) {
      _instance = new SharedPreferencesUtil._internal();
    }
    return _instance;
  }

  getSp() async {
    await SharedPreferences.getInstance().then((sharedPreferences) {
      this.sharedPreferences = sharedPreferences;
    }).catchError((error) {
      print(error.toString());
    });
  }

  setInt(String key, int value) async {
    if (sharedPreferences == null) {
      return;
    }
    await sharedPreferences.setInt(key, value);
  }

  Future<int> getInt(String key) async {
    if (sharedPreferences == null) {
      return null;
    }
    return sharedPreferences.getInt(key);
  }

  setString(String key, String value) async {
    if (sharedPreferences == null) {
      return;
    }
    await sharedPreferences.setString(key, value);
  }

  Future<String> getString(String key) async {
    if (sharedPreferences == null) {
      return null;
    }
    return sharedPreferences.getString(key) ?? "null";
  }

  setStringList(String key, List<String> value) async {
    if (sharedPreferences == null) {
      return;
    }
    await sharedPreferences.setStringList(key, value);
  }

  Future<List<String>> getStringList(String key) async {
    if (sharedPreferences == null) {
      return null;
    }
    return sharedPreferences.getStringList(key) ?? new List<String>();
  }

  setBool(String key, bool value) async {
    if (sharedPreferences == null) {
      return;
    }
    await sharedPreferences.setBool(key, value);
  }

  Future<bool> getBool(String key) async {
    if (sharedPreferences == null) {
      return null;
    }
    return sharedPreferences.getBool(key);
  }

  setDouble(String key, double value) async {
    if (sharedPreferences == null) {
      return;
    }
    await sharedPreferences.setDouble(key, value);
  }

  Future<double> getDouble(String key) async {
    if (sharedPreferences == null) {
      return null;
    }
    return sharedPreferences.getDouble(key);
  }
}
